package com.alingrad.android.froyoengine.graphics.renderable;

import javax.microedition.khronos.opengles.GL10;

import com.alingrad.android.froyoengine.collisions.CollisionMaskData;
import com.alingrad.android.froyoengine.util.GLHelper;

public class Polygon extends Primitive {
	public CollisionMaskData mData;
	
	public Polygon(float[] xPoints, float[] yPoints) {
		if (xPoints.length < 3) 
			throw new IllegalArgumentException("Polygon must have atleast 3 vertices.");
		float[] vertices = new float[xPoints.length * 3];
		float minx = xPoints[0];
		float maxx = xPoints[0];
		float miny = yPoints[0];
		float maxy = yPoints[0];
		int j = 0;
		for (int i = 0; i < xPoints.length; i++) {
			vertices[j] = xPoints[i];
			vertices[j + 1] = yPoints[i];
			vertices[j + 2] = 0f;
			j += 3;
			if (minx > xPoints[i])
				minx = xPoints[i];
			if (maxx < xPoints[i])
				maxx = xPoints[i];
			if (miny > yPoints[i])
				miny = yPoints[i];
			if (maxy < yPoints[i])
				maxy = yPoints[i];
		}
		int width = (int)(maxx - minx);
		int height = (int)(maxy - miny);
		mData = new CollisionMaskData(width / 2, height / 2, width, height);
		createVertexBuffer(vertices);
	}

	@Override
	public CollisionMaskData getCollisionMaskData() {
		return mData;
	}
	
	@Override
	public void draw(GL10 gl, float x, float y, float z, float scaleX,
			float scaleY, float rotation) {
		gl.glPushMatrix();
			GLHelper.setMatrix(gl, x, y, z, scaleX, scaleY, rotation);
			GLHelper.setColor(gl, mColor);
			gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
			gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
			gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, mVertexBuffer.capacity());
		gl.glPopMatrix();
	}
}
